package org.sun.log_manager_study.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.Optional;
import java.util.UUID;

@Component
public class RequestLoggingFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(RequestLoggingFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        long start = System.currentTimeMillis();
        String requestId = UUID.randomUUID().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String query = Optional.ofNullable(request.getQueryString()).orElse("");
        String clientIp = clientIp(request);
        String username = resolveUsername(request);

        MDC.put("requestId", requestId);
        MDC.put("method", method);
        MDC.put("path", uri);
        if (!query.isEmpty()) {
            MDC.put("query", query);
        }
        MDC.put("clientIp", clientIp);
        MDC.put("username", username);

        try {
            filterChain.doFilter(request, response);
        } finally {
            long duration = System.currentTimeMillis() - start;
            int status = safeStatus(response);
            MDC.put("status", String.valueOf(status));
            MDC.put("durationMs", String.valueOf(duration));
            log.info("request completed");
            MDC.clear();
        }
    }

    private String clientIp(HttpServletRequest request) {
        String xff = request.getHeader("X-Forwarded-For");
        if (xff != null && !xff.isEmpty()) {
            // take first ip
            int idx = xff.indexOf(',');
            return idx > 0 ? xff.substring(0, idx).trim() : xff.trim();
        }
        String ip = request.getHeader("X-Real-IP");
        if (ip != null && !ip.isEmpty()) return ip;
        return request.getRemoteAddr();
    }

    private String resolveUsername(HttpServletRequest request) {
        // 1) From Principal (works with container auth/Spring Security)
        Principal p = request.getUserPrincipal();
        if (p != null && p.getName() != null && !p.getName().isEmpty()) {
            return p.getName();
        }
        // 2) From common headers (custom upstream)
        String[] headerKeys = new String[]{"X-User", "X-Username", "X-Auth-User"};
        for (String k : headerKeys) {
            String v = request.getHeader(k);
            if (v != null && !v.isEmpty()) return v;
        }
        // 3) From query parameter as fallback
        String qp = request.getParameter("username");
        if (qp != null && !qp.isEmpty()) return qp;
        // Default
        return "anonymous";
    }

    private int safeStatus(HttpServletResponse response) {
        try {
            return response.getStatus();
        } catch (Throwable ignored) {
            return 200;
        }
    }
}

